package com.by.course.config.web.interceptor;

import com.by.course.config.web.jwt.JwtService;
import com.by.course.config.web.jwt.PassToken;
import com.by.course.config.web.jwt.UserUtil;
import com.by.course.entity.bo.BaseUser;
import com.by.course.execption.BusinessException;
import com.by.course.serivce.BaseUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zhd
 * @date 2023/08/27 14:49
 **/
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private JwtService jwtService;

    @Resource
    private CompoundStrategy compoundStrategy;

    @Resource
    private BaseUserService baseUserService;

    private static final String TOKEN_PREFIX = "Bearer:";

    /**
     * @param httpServletRequest  request
     * @param httpServletResponse response
     * @param object              obj
     * @return boolean
     * @author zhd
     * @date 2023/08/27 14:50
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             @Nullable HttpServletResponse httpServletResponse,
                             @Nullable Object object) {
        String token = httpServletRequest.getHeader("Authorization");
        String requestUri = httpServletRequest.getRequestURI();

        log.info("preHandle requestUri:{}, token:{}", requestUri, token);

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        // 验证url是否需要验证
        if (compoundStrategy.verify(httpServletRequest.getRequestURI())) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 如果方法上有@PassToken注解则不验证token
        if (verifyPassToken(method)) {
            return true;
        }

        return true;
//        if (token.startsWith(TOKEN_PREFIX)) {
//            token = token.substring(7);
//        }

//        if (StringUtils.isEmpty(token)) {
//            throw new BusinessException("token is null " + requestUri, ErrEnum.TOKEN_ERR.getCode());
//        }
//
//        Claims claims = jwtService.verifyJwt(token);
//        if (claims != null) {
//            Long userId = claims.get("userId", Long.class);
//            String openId = claims.get("openId", String.class);
//            log.info("preHandle requestUri:{}, token:{}, openId:{}, userId:{}", requestUri, token, openId, userId);
//        }
//
//        if (claims == null) {
//            throw new BusinessException("token invalid" + requestUri + " token: " + token, ErrEnum.TOKEN_ERR.getCode());
//        }
//
//        boolean tokenExpired = jwtService.isTokenExpired(token);
//
//        if (tokenExpired) {
//            throw new BusinessException("token expired" + requestUri + " token: " + token, ErrEnum.TOKEN_ERR.getCode());
//        }
//
//        Long userId = claims.get("userId", Long.class);
//        String openId = claims.get("openId", String.class);
//        verifyUser(userId);
//        UserToken user = new UserToken();
//        user.setUserId(userId);
//        user.setOpenId(openId);
//        UserUtil.setUser(user);
//        return true;
    }

    private void verifyUser(Long userId) {
        BaseUser user = baseUserService.getById(userId);
        if (user == null) {
            throw new BusinessException("verifyUser not exit " + userId, 403);
        }
    }


    private boolean verifyPassToken(Method method) {
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            return passToken.required();
        }
        return false;
    }

    @Override
    public void afterCompletion(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response,
                                @Nullable Object handler, @Nullable Exception ex) {
        try {
            UserUtil.remove();
        } catch (Exception e) {
            log.info("afterCompletion error:", e);
        }
    }
}
